package stock;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.hibernate.Session;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import stock.model.LTModel;

@Component
public class StockClsService implements StockClsServiceInterface {

	public static List<StockCls> listStockctl = null;

	@Transactional
	@Scheduled(cron = "0 */5 * * * ?")
	public void loadStocCls() {

//		if (listStockctl != null) {
//			return;
//		}
		System.out.println("加载所有cls数据到内存中,每5分钟执行一次");
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		listStockctl = session1.createQuery("from StockCls t").list();

		List<LTModel> listLt = session1.createQuery("from LTModel t").list();

		String sql4 = "update ltmodel set zt_content =?0,duolt=?1 where code1=?2 ";

		String sql6 = "select count(*) from stockqq t  where t.code =?0 and t.zhangdiefu>=8  ORDER BY  t.date desc limit 0,10";

		for (int k = 0; k < listLt.size(); k++) {
			for (int i = 0; i < listStockctl.size(); i++) {
				if (listLt.get(k).getCode1().equals(listStockctl.get(i).getCode())) {

					String temp = session1.createSQLQuery(sql6).setParameter(0, listStockctl.get(i).getCode()).uniqueResult().toString();

					// System.out.println("当前code" + listStockctl.get(i).getCode());
					session1.getTransaction().begin();
					session1.createSQLQuery(sql4).setParameter(0, listStockctl.get(i).getZtContent()).setParameter(1, temp).setParameter(2, listStockctl.get(i).getCode()).executeUpdate();
					session1.getTransaction().commit();
					break;
				}

			}
		}

		//System.out.println(listStockctl.size());
		session1.clear();
		session1.close();
	}

	@Transactional
	// @Scheduled(cron = "0 0 22 * * ?")
	@Scheduled(cron = "0 20 22 * * ?")
	public void getStocCls() {
		System.out.println("加载每日财联社个股概念数据");

		String sql = "select DISTINCT(code),name,diqv from stock ";
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<String[]> list = session1.createSQLQuery(sql).list();
		List<String> lists = new ArrayList<String>();
		String all = "";

		for (int i = 0; i < list.size(); i++) {

			Object[] json = list.get(i);
			String code = json[0] + "";
			String name = json[1] + "";
			String diqv = json[2] + "";

			String sql1 = "from StockCls t where t.code = ?0";
			List<StockCls> list2 = session1.createQuery(sql1).setParameter(0, code.replace("sz", "").replace("sh", "")).list();

			if (list2 == null || list2.size() <= 0) {
				continue;
			}

			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			try {
				System.out.println("抓取" + i + "==" + code);
				// 创建WebClient实例，指定信任所有SSL/TLS证书的工厂
				String[] lista = getZTnoteDayGN(code);

				if ("无".equals(lista[1])) {
					continue;
				}

				StockCls sc = new StockCls();
				sc.setCode(code.replace("sz", "").replace("sh", ""));
				sc.setName(name);
				sc.setGn(lista[1]);
				sc.setCreateTime(DateTools.getCurrentDateTime());
				sc.setDiqv(diqv);
				sc.setShizhi(lista[0]);
//				sc.setZtContent(str);
				code = code.replace("sz", "").replace("sh", "");

				session1.beginTransaction();
				if (null == list2 && list2.size() <= 0) {
					session1.save(sc);
				} else {
					list2.get(0).setCreateTime(DateTools.getCurrentDateTime());
					list2.get(0).setGn(lista[1]);
					list2.get(0).setShizhi(lista[0]);
					session1.update(list2.get(0));
				}
				session1.getTransaction().commit();
				session1.clear();

			} catch (Exception e) {
				System.out.println("----------------------------");
				e.printStackTrace();
			} finally {
				// driver.quit();
			}
		}
		session1.close();

	}

	public static WebDriver driver = null;

	public static WebDriver getdriver() {

		if (driver == null) {
			File f = new File("D:\\\\chromedriver\\\\chromedriver-win64133\\\\chromedriver.exe");
			if (f.exists()) {
				System.setProperty("webdriver.chrome.driver", "D:\\\\chromedriver\\\\chromedriver-win64133\\\\chromedriver.exe");
			} else {
				System.setProperty("webdriver.chrome.driver", "/opt/chromedriver-linux64/chromedriver");
			}
			// 指定Chrome浏览器核心

			// 创建Chrome浏览器驱动
			// 配置Chrome选项
			ChromeOptions options = new ChromeOptions();
			options.addArguments("--headless"); // 无界面运行
			options.addArguments("--no-sandbox");
			options.addArguments("--disable-gpu");
			options.addArguments("--disable-dev-shm-usage");
			// options.addArguments("--whitelisted-ips");
			// options.addArguments("--verbose");
			// options.addArguments("--allowed-ips");

			// 创建Chrome浏览器驱动
			driver = new ChromeDriver(options);
		}
		return driver;
	}

	@Override
	public void getStocCls1() {
		// TODO Auto-generated method stub
		getStocCls();
	}

	@Transactional
	@Scheduled(cron = "0 30 18 * * ?")
	public void getStocCls2() {
		System.out.println("加载每日涨停概念");
		String sql = "select DISTINCT(code),name,diqv from stock ";
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<String[]> list = session1.createSQLQuery(sql).list();
		List<String> lists = new ArrayList<String>();
		String all = "";
		for (int i = 0; i < list.size(); i++) {
			Object[] json = list.get(i);
			String code = json[0] + "";
			String name = json[1] + "";
			String diqv = json[2] + "";
			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			if (i % 500 == 0 && i != 0) {
				all += code + "";
				System.out.println(all);
				lists.add(all);
				all = "";
				continue;
			}
			if (i == list.size() - 1) {
				all += code + "";
				System.out.println(all);
				lists.add(all);
				break;
			}
			all += code + ",";
		}
		JSONArray jsonall = new JSONArray();
		for (int i = 0; i < lists.size(); i++) {
			JSONArray jsona = StockClsService.getCcc(lists.get(i));
			jsonall.addAll(jsona);
		}
		System.out.println("共有符合：" + jsonall.size());
		try {
			// driver.quit();
			driver = null;
		} catch (Exception e) {
			// TODO: handle exception

		}

		for (int j = 0; j < jsonall.size(); j++) {
			for (int i = 0; i < list.size(); i++) {
				Object[] json = list.get(i);
				String code = json[0] + "";
				String name = json[1] + "";
				String diqv = json[2] + "";

				JSONObject js = jsonall.getJSONObject(j);
				StockQQ stockqq = (StockQQ) js.toBean(js, StockQQ.class);
				if (stockqq.getCode().equals(code)) {
					System.out.println("符合：" + stockqq.getCode() + ":" + stockqq.getZhangdiefu());
					System.out.println("找到匹配");
					if (Float.parseFloat(stockqq.getZhangdiefu()) >= 8f) {
						session1.getTransaction().begin();
						if ("0".equals(diqv)) {
							code = "sh" + code;
						} else {
							code = "sz" + code;
						}
						String allzt = getZTnote(code);
						stockqq.setZtNote(allzt.replaceAll(" ", ""));
						System.out.println(stockqq.getCode() + "==" + stockqq.getZhangdiefu());
						String sql2 = "delete from stockqq where code = ?0 and date = ?1 ";
						session1.createSQLQuery(sql2).setParameter(0, stockqq.getCode()).setParameter(1, stockqq.getDate()).executeUpdate();
						stockqq.setCreateTime(DateTools.getCurrentDateTime());
						stockqq.setZtNote(allzt);
						session1.save(stockqq);
						String sql3 = "update stock_cls set zt_content = ?0 where code = ?1 ";
						session1.createSQLQuery(sql3).setParameter(0, allzt.replaceAll(" ", "")).setParameter(1, stockqq.getCode()).executeUpdate();
						String sql4 = "update ltmodel set zt_content =?0 where code1=?1";
						session1.createSQLQuery(sql4).setParameter(0, allzt.replaceAll(" ", "")).setParameter(1, stockqq.getCode()).executeUpdate();
						session1.getTransaction().commit();
						session1.clear();
						break;
					}
				}

			}

		}
		loadStocCls();
		session1.close();
		driver.quit();

	}

	public static JSONArray getCcc(String codearr) {

		JSONArray jsonarrr = new JSONArray();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet("http://qt.gtimg.cn/q=" + codearr);
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String[] arary = codearr.split(",");
		try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String responseData = EntityUtils.toString(entity);
				// 对返回的responseData进行处理
				String[] str = responseData.split(";");
				for (int i = 0; i < str.length; i++) {
					String[] str1 = str[i].split("~");
					if (str1.length <= 1) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("name", str1[1]);
					json.put("dqj", str1[3]);
					json.put("code", str1[2]);
					json.put("zhangdiefu", str1[32]);
					json.put("cjje", str1[37]);
					if (Float.parseFloat(str1[32]) < 8f) {
						continue;
					}

					json.put("zuigao", str1[33]);
					json.put("zuidi", str1[34]);
					json.put("huanshoulv", str1[38]);
					json.put("shizhi", str1[45]);
					json.put("date", str1[30].substring(0, 8));
					jsonarrr.add(json);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return jsonarrr;
	}

	public String getZTnote(String code) {
		// 获取标签内容
		String str = "";
		try {

			// 创建WebClient实例，指定信任所有SSL/TLS证书的工厂
			String url = "https://www.cls.cn/stock?code=" + code;

			if (driver == null) {
				driver = getdriver();
			}
			driver.get(url);
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			List<WebElement> webe = null;
			try {
				webe = driver.findElements(By.xpath("//div[@class='f-s-14 list-more-button more-button']"));

				webe.get(0).click();
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			List<WebElement> elements = driver.findElements(By.xpath("//div[@class='b-c-e6e7ea telegraph-list']//a"));

			for (WebElement element : elements) {

				String content = element.getText();
				if (content.indexOf("涨停原因") > -1) {
					System.out.println(element.getText());
					int t0 = element.getText().indexOf(":");
					int t1 = element.getText().length();
					System.out.println(element.getText().substring(t0 + 1, t1));
					String temp = element.getText().substring(t0 + 1, t1);

					if (str.indexOf(temp) >= -1) {

						str = temp;
					} else {
						str += temp;
					}
				}
				if (content.indexOf("大涨原因") > -1) {
					System.out.println(element.getText());
					int t0 = element.getText().indexOf("：");
					int t1 = element.getText().length();
					System.out.println(element.getText().substring(t0 + 1, t1));
					String temp = element.getText().substring(t0 + 1, t1);

					if (str.indexOf(temp) >= -1) {

						str = temp;

					} else {
						str += temp;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// driver.quit();
		return str;
	}

	public String[] getZTnoteDayGN(String code) {
		// 获取标签内容
		String str = "";

		String[] strarray = new String[] { "0", "无" };
		List<String> lista = new ArrayList<String>();
		try {

			// 创建WebClient实例，指定信任所有SSL/TLS证书的工厂
			String url = "https://www.cls.cn/stock?code=" + code;

			if (driver == null) {
				driver = getdriver();
			}
			driver.get(url);
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			List<WebElement> elements = driver.findElements(By.xpath("//div[@class='m-b-10']//a"));
			List<WebElement> elements2 = driver.findElements(By.xpath("//div[@class='p-r m-b-10 quote-text-border']//span"));
			// 执行点击操作
			String shizhi = "0";
			lista.add(shizhi);
			for (int j = 0; j < elements2.size(); j++) {
				String str1 = elements2.get(j).getText();

				if (str1.equals("总市值")) {
					System.out.println(code + "::" + str1);
					shizhi = elements2.get(j + 1).getText().replaceAll("亿", "");
					strarray[0] = shizhi;
					break;
				}
			}
			List<String> listn = new ArrayList<String>();
			// 获取标签内容
			for (WebElement element : elements) {
				listn.add(element.getText());
			}
			//System.out.println(String.join(",", listn));
			strarray[1] = String.join(",", listn);

		} catch (Exception e) {
			e.printStackTrace();
		}

		// driver.quit();
		return strarray;
	}

	@Override
	public JSONArray getGnStockList(JSONObject json) {
		// TODO Auto-generated method stub

		String text5 = json.getString("text5").replace("，", ",");

		String[] str = text5.split(",");
		String sql = "";
		if (str.length >= 1) {
			if (str.length == 1) {
				sql = "from StockCls t where t.gn  like '%" + str[0] + "%' ";
			}
			if (str.length == 2) {
				sql = "from StockCls t where t.gn  like '%" + str[0] + "%' and t.gn like '%" + str[1] + "%'";
			}
			if (str.length == 3) {
				sql = "from StockCls t where t.gn  like '%" + str[0] + "%' and t.gn like '%" + str[1] + "%' and t.gn like '%" + str[2] + "%'";
			}
			Session session1 = ContextUtil.getSessionFactory1().openSession();
			return JSONArray.fromObject(session1.createQuery(sql).list());
		}

		return null;
	}

	@Override
	public void getStocCls21() {
		// TODO Auto-generated method stub
		LocalDate yesterday = LocalDate.now().minusDays(1);
		// 将日期格式化为整数（例如：yyyyMMdd）
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		int yesterdayAsInt = Integer.parseInt(yesterday.format(formatter));
		String sql = "from StockQQ  t where t.date =?0 and t.zhangdiefu >9 ";
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<StockQQ> list = session1.createQuery(sql).setParameter(0, yesterdayAsInt + "").list();

		for (int i = 0; i < list.size(); i++) {

			String code = list.get(i).getCode();
			System.out.println(code);
			if (list.get(i).getCode().indexOf("6") == 0) {

				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			String str = getZTnote(code);
			System.out.println(code + str);
			list.get(i).setZtNote(str);
			session1.update(list.get(i));

		}

		session1.clear();
		session1.close();

	}

}
